import {Popconfirm} from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import React, {useState, useEffect} from 'react';
import styles from "@/pages/Info/Edit/style.less";

const TableForm = ({addUserList, protocolUserItems=[], saveFunction}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);

  let columns = [
    {
      title: '工号',
      dataIndex: 'employeeId',
      disabled: true
    },
    {
      title: '姓名',
      dataIndex: 'employeeName',
      disabled: true
    },
    {
      title: '公司',
      dataIndex: 'corpName',
      disabled: true
    },
    {
      title: '部门',
      dataIndex: 'orgName',
      disabled: true
    },
    {
      title: '操作',
      key: 'action',
      width: '150px',
      render: (text, record) => {
        return (
          <Popconfirm title="是否确定删除？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record)}>
            <a>删除</a>
          </Popconfirm>
        )
      }
    },
  ];

  useEffect(()=>{
    setData(protocolUserItems.map((item, index) => ({key: 'had' + index, ...item})));
  },[protocolUserItems]);

  useEffect(() => {
    setLoading(true);
    if (addUserList.length > 0) {
      let newData = [...data];
      for (let i = 0; i < addUserList.length; i++) {
        let isContinue = false;
        for (let a = 0; a < data.length; a++) {
          if (data[a].oid === addUserList[i].oid)
            isContinue = true;
        }
        if (isContinue)
          continue;
        newData.push({
          key: addUserList[i].oid || i,
          employeeId: addUserList[i].code || addUserList[i].employeeId,
          corpName: addUserList[i].orgname || addUserList[i].corpName,
          orgName: addUserList[i].unitname || addUserList[i].orgName,
          employeeName: addUserList[i].name || addUserList[i].employeeName,
        });
      }
      saveFunction(newData);
    }
    setLoading(false);
  }, [addUserList]);

  const remove = (e, record) => {
    setLoading(true);
    const newData = [...data];
    let datas = newData.filter(item => item.key !== record.key);
    saveFunction(datas);
    setLoading(false);
  };

  return (
    <>
      <ProTable
        toolBarRender={false}
        loading={loading}
        columns={columns}
        dataSource={data}
        search={false}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />

    </>
  )
};

export default TableForm;

